<template>
  <div class="list-detail-data-source-config">
    <div style="margin-bottom: 16px;">
      <a-button type="primary" @click="showDataSourceModal = true">
        选择数据源
      </a-button>
      <a-button style="margin-left: 8px;" @click="clearAllFields" type="default">
        清空数据源
      </a-button>
    </div>

    <a-table 
      :columns="columns" 
      :data-source="fields" 
      :pagination="false"
      :scroll="{ y: 400 }"
      :row-key="(record) => record.fieldKey"
      class="fixed-height-table"
    >
      <template #headerCell="{ column }">
        <template v-if="column.key === 'queryChecked'">
          <a-checkbox 
            :indeterminate="queryIndeterminate"
            :checked="queryCheckAll"
            @change="onCheckAllChange('query')"
          >
            查询字段
          </a-checkbox>
        </template>
        <template v-else-if="column.key === 'listChecked'">
          <a-checkbox 
            :indeterminate="listIndeterminate"
            :checked="listCheckAll"
            @change="onCheckAllChange('list')"
          >
            列表字段
          </a-checkbox>
        </template>
        <template v-else-if="column.key === 'headerChecked'">
          <a-checkbox 
            :indeterminate="headerIndeterminate"
            :checked="headerCheckAll"
            @change="onCheckAllChange('header')"
          >
            表头字段
          </a-checkbox>
        </template>
        <template v-else-if="column.key === 'detailQueryChecked'">
          <a-checkbox 
            :indeterminate="detailQueryIndeterminate"
            :checked="detailQueryCheckAll"
            @change="onCheckAllChange('detailQuery')"
          >
            表体查询字段
          </a-checkbox>
        </template>
        <template v-else-if="column.key === 'detailListChecked'">
          <a-checkbox 
            :indeterminate="detailListIndeterminate"
            :checked="detailListCheckAll"
            @change="onCheckAllChange('detailList')"
          >
            表体列表字段
          </a-checkbox>
        </template>
        <template v-else>
          {{ column.title }}
        </template>
      </template>
      
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'fieldName'">
          <a-tooltip :title="record.fieldName">
            <span class="ellipsis-cell">{{ record.fieldName }}</span>
          </a-tooltip>
        </template>
        
        <template v-else-if="column.key === 'description'">
          <a-tooltip :title="record.description">
            <span class="ellipsis-cell">{{ record.description }}</span>
          </a-tooltip>
        </template>
        
        <template v-else-if="column.key === 'queryChecked'">
          <a-checkbox 
            :checked="record.queryChecked" 
            @change="(e) => { record.queryChecked = e.target.checked; onFieldChange(); updateCheckAllStates(); }"
          ></a-checkbox>
        </template>
        
        <template v-else-if="column.key === 'listChecked'">
          <a-checkbox 
            :checked="record.listChecked" 
            @change="(e) => { record.listChecked = e.target.checked; onFieldChange(); updateCheckAllStates(); }"
          ></a-checkbox>
        </template>
        
        <template v-else-if="column.key === 'headerChecked'">
          <a-checkbox 
            :checked="record.headerChecked" 
            @change="(e) => { record.headerChecked = e.target.checked; onFieldChange(); updateCheckAllStates(); }"
          ></a-checkbox>
        </template>
        
        <template v-else-if="column.key === 'detailQueryChecked'">
          <a-checkbox 
            :checked="record.detailQueryChecked" 
            @change="(e) => { record.detailQueryChecked = e.target.checked; onFieldChange(); updateCheckAllStates(); }"
          ></a-checkbox>
        </template>
        
        <template v-else-if="column.key === 'detailListChecked'">
          <a-checkbox 
            :checked="record.detailListChecked" 
            @change="(e) => { record.detailListChecked = e.target.checked; onFieldChange(); updateCheckAllStates(); }"
          ></a-checkbox>
        </template>
        
        <!-- <template v-else-if="column.key === 'componentType'">
          <a-select 
            :value="record.componentType" 
            :options="componentTypeOptions"
            size="small"
            style="width: 120px;"
            @change="(value) => { record.componentType = value; onFieldChange(); }"
          />
        </template> -->
      </template>
    </a-table>

    <!-- 数据源选择弹窗 -->
    <DataSourceSelectionModal 
      v-model:open="showDataSourceModal"
      @confirm="handleDataSourceConfirm"
    />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import DataSourceSelectionModal from '../DataSourceSelectionModal.vue'

// 定义组件属性
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({
      queryFields: [],
      listFields: [],
      headerFields: [],
      detailQueryFields: [],
      detailListFields: []
    })
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue'])

// 组件类型选项
const componentTypeOptions = [
  { label: 'Input', value: 'Input' },
  { label: 'InputNumber', value: 'InputNumber' },
  { label: 'Select', value: 'Select' },
  { label: 'DatePicker', value: 'DatePicker' },
  { label: 'Switch', value: 'Switch' }
]

// 表格列定义
const columns = [
  {
    title: '字段名',
    dataIndex: 'fieldName',
    key: 'fieldName'
  },
  {
    title: '字段描述',
    dataIndex: 'description',
    key: 'description'
  },
  {
    title: '查询字段',
    dataIndex: 'queryChecked',
    key: 'queryChecked'
  },
  {
    title: '列表字段',
    dataIndex: 'listChecked',
    key: 'listChecked'
  },
  {
    title: '表头字段',
    dataIndex: 'headerChecked',
    key: 'headerChecked'
  },
  {
    title: '表体查询字段',
    dataIndex: 'detailQueryChecked',
    key: 'detailQueryChecked'
  },
  {
    title: '表体列表字段',
    dataIndex: 'detailListChecked',
    key: 'detailListChecked'
  },
//   {
//     title: '数据类型',
//     dataIndex: 'componentType',
//     key: 'componentType'
//   }
]

// 数据字段
const fields = ref([])

// 控制弹窗显示
const showDataSourceModal = ref(false)

// 全选状态
const queryCheckAll = ref(false)
const listCheckAll = ref(false)
const headerCheckAll = ref(false)
const detailQueryCheckAll = ref(false)
const detailListCheckAll = ref(false)

// 半选状态
const queryIndeterminate = ref(false)
const listIndeterminate = ref(false)
const headerIndeterminate = ref(false)
const detailQueryIndeterminate = ref(false)
const detailListIndeterminate = ref(false)

// 处理全选/取消全选
const onCheckAllChange = (type) => {
  const checked = !getCheckAllState(type)
  setCheckAllState(type, checked)
  
  fields.value = fields.value.map(item => {
    switch (type) {
      case 'query':
        item.queryChecked = checked
        break
      case 'list':
        item.listChecked = checked
        break
      case 'header':
        item.headerChecked = checked
        break
      case 'detailQuery':
        item.detailQueryChecked = checked
        break
      case 'detailList':
        item.detailListChecked = checked
        break
    }
    return item
  })
  
  updateCheckAllStates()
  onFieldChange()
}

// 获取全选状态
const getCheckAllState = (type) => {
  switch (type) {
    case 'query':
      return queryCheckAll.value
    case 'list':
      return listCheckAll.value
    case 'header':
      return headerCheckAll.value
    case 'detailQuery':
      return detailQueryCheckAll.value
    case 'detailList':
      return detailListCheckAll.value
    default:
      return false
  }
}

// 设置全选状态
const setCheckAllState = (type, checked) => {
  switch (type) {
    case 'query':
      queryCheckAll.value = checked
      break
    case 'list':
      listCheckAll.value = checked
      break
    case 'header':
      headerCheckAll.value = checked
      break
    case 'detailQuery':
      detailQueryCheckAll.value = checked
      break
    case 'detailList':
      detailListCheckAll.value = checked
      break
  }
}

// 更新全选状态
const updateCheckAllStates = () => {
  if (fields.value.length === 0) {
    // 如果没有数据，则重置所有全选状态
    queryCheckAll.value = false
    listCheckAll.value = false
    headerCheckAll.value = false
    detailQueryCheckAll.value = false
    detailListCheckAll.value = false
    
    queryIndeterminate.value = false
    listIndeterminate.value = false
    headerIndeterminate.value = false
    detailQueryIndeterminate.value = false
    detailListIndeterminate.value = false
    return
  }
  
  // 计算各个字段的选中状态
  const queryCheckedCount = fields.value.filter(item => item.queryChecked).length
  const listCheckedCount = fields.value.filter(item => item.listChecked).length
  const headerCheckedCount = fields.value.filter(item => item.headerChecked).length
  const detailQueryCheckedCount = fields.value.filter(item => item.detailQueryChecked).length
  const detailListCheckedCount = fields.value.filter(item => item.detailListChecked).length
  
  // 更新查询字段全选状态
  queryIndeterminate.value = queryCheckedCount > 0 && queryCheckedCount < fields.value.length
  queryCheckAll.value = queryCheckedCount === fields.value.length
  
  // 更新列表字段全选状态
  listIndeterminate.value = listCheckedCount > 0 && listCheckedCount < fields.value.length
  listCheckAll.value = listCheckedCount === fields.value.length
  
  // 更新表头字段全选状态
  headerIndeterminate.value = headerCheckedCount > 0 && headerCheckedCount < fields.value.length
  headerCheckAll.value = headerCheckedCount === fields.value.length
  
  // 更新表体查询字段全选状态
  detailQueryIndeterminate.value = detailQueryCheckedCount > 0 && detailQueryCheckedCount < fields.value.length
  detailQueryCheckAll.value = detailQueryCheckedCount === fields.value.length
  
  // 更新表体列表字段全选状态
  detailListIndeterminate.value = detailListCheckedCount > 0 && detailListCheckedCount < fields.value.length
  detailListCheckAll.value = detailListCheckedCount === fields.value.length
}

// 处理数据源确认事件
const handleDataSourceConfirm = (data) => {
  let fieldId = Date.now()
  data.selectedFields.forEach(field => {
    // 检查是否已经存在相同的字段
    const existingFieldIndex = fields.value.findIndex(f => 
      f.fieldName === field.label
    )
    
    if (existingFieldIndex === -1) {
      // 只有当字段不存在时才添加
      const fieldRecord = {
        fieldKey: `${fieldId++}`,
        fieldName: field.label,
        description: field.description || '',
        sourcePath: data.path,
        sourceMethod: data.method,
        queryChecked: false,
        listChecked: false,
        headerChecked: false,
        detailQueryChecked: false,
        detailListChecked: false,
        componentType: 'Input'
      }
      
      fields.value.push(fieldRecord)
      console.log("🚀 ~ handleDataSourceConfirm ~ fields.value:", fields.value)
      
    }
  })
  
  updateCheckAllStates()
  updateModelValue()
}

// 字段变更时更新modelValue
const onFieldChange = () => {
  updateModelValue()
}

// 更新modelValue
const updateModelValue = () => {
  const queryFields =[]
  const listFields = []
  const headerFields = []
  const detailQueryFields = []
  const detailListFields = []

  fields.value.forEach(field => {
    if(field.queryChecked){
        queryFields.push(field)
    };
    if(field.listChecked){
        listFields.push(field)
    };
    if(field.headerChecked){
        headerFields.push(field)
    }
    if(field.detailQueryChecked){
        detailQueryFields.push(field)
    }
    if(field.detailListChecked){
        detailListFields.push(field)
    }
  })




  let modelValue = {
    queryFields,
    listFields,
    headerFields,
    detailQueryFields,
    detailListFields
  }

  console.log("🚀 ~ updateModelValue ~ modelValue:", modelValue)


  
  emit('update:modelValue',modelValue )
}

// 监听props变化
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    // 将所有字段合并到一个数组中
    const allFieldsMap = new Map()
    
    // 先把当前所有字段放入map中
    fields.value.forEach(field => {
      const key = `${field.sourcePath}-${field.sourceMethod}-${field.fieldName}`
      allFieldsMap.set(key, {
        ...field,
        queryChecked: false,
        listChecked: false,
        headerChecked: false,
        detailQueryChecked: false,
        detailListChecked: false
      })
    })
    
    // 添加查询字段
    newVal.queryFields?.forEach(field => {
      const key = `${field.sourcePath}-${field.sourceMethod}-${field.fieldName}`
      if (!allFieldsMap.has(key)) {
        allFieldsMap.set(key, {
          ...field,
        })
      } 
      allFieldsMap.get(key).queryChecked = true
    })
    
    // 添加列表字段
    newVal.listFields?.forEach(field => {
      const key = `${field.sourcePath}-${field.sourceMethod}-${field.fieldName}`
      if (!allFieldsMap.has(key)) {
        allFieldsMap.set(key, {
          ...field,
          queryChecked: false,
          listChecked: false,
          headerChecked: false,
          detailQueryChecked: false,
          detailListChecked: false
        })
      }
      allFieldsMap.get(key).listChecked = true
    })
    
    // 添加表头字段
    newVal.headerFields?.forEach(field => {
      const key = `${field.sourcePath}-${field.sourceMethod}-${field.fieldName}`
      if (!allFieldsMap.has(key)) {
        allFieldsMap.set(key, {
          ...field,
          queryChecked: false,
          listChecked: false,
          headerChecked: false,
          detailQueryChecked: false,
          detailListChecked: false
        })
      }
      allFieldsMap.get(key).headerChecked = true
    })
    
    // 添加表体查询字段
    newVal.detailQueryFields?.forEach(field => {
      const key = `${field.sourcePath}-${field.sourceMethod}-${field.fieldName}`
      if (!allFieldsMap.has(key)) {
        allFieldsMap.set(key, {
          ...field,
          queryChecked: false,
          listChecked: false,
          headerChecked: false,
          detailQueryChecked: false,
          detailListChecked: false
        })
      }
      allFieldsMap.get(key).detailQueryChecked = true
    })
    
    // 添加表体列表字段
    newVal.detailListFields?.forEach(field => {
      const key = `${field.sourcePath}-${field.sourceMethod}-${field.fieldName}`
      if (!allFieldsMap.has(key)) {
        allFieldsMap.set(key, {
          ...field,
          queryChecked: false,
          listChecked: false,
          headerChecked: false,
          detailQueryChecked: false,
          detailListChecked: false
        })
      }
      allFieldsMap.get(key).detailListChecked = true
    })
    
    fields.value = Array.from(allFieldsMap.values())
    updateCheckAllStates()
  }
}, { deep: true, immediate: true })



// 清空所有字段
const clearAllFields = () => {
  fields.value = []
  updateCheckAllStates()
  updateModelValue()
}
</script>

<style scoped>
.list-detail-data-source-config {
  padding: 10px 0;
}

/* 添加省略显示样式 */
.ellipsis-cell {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.fixed-height-table {
  min-height: 450px;
}

:deep(.ant-table-body) {
  min-height: 400px;
}
</style>